<template>
  <view w-full box-border px-20rpx>
    <view bg="#fff" rounded-20rpx>
      <nut-form ref="formRef" :model-value="form" :rules="rules">
        <nut-form-item prop="schoolName" label="学校名称" style="border-bottom: 1px solid #eee" label-width="160rpx">
          <nut-input v-model="form.schoolName" placeholder="请输入" type="text" />
        </nut-form-item>

        <nut-form-item prop="schoolAdress" label="学校地址" label-width="160rpx">
          <nut-input v-model="form.schoolAdress" class="nut-input-text" placeholder="请输入" type="text" />
        </nut-form-item>
      </nut-form>
    </view>
  </view>
  <view position-fixed bottom-46rpx w-full z-999 px-40rpx box-border>
    <view
      w-670rpx
      h-100rpx
      rounded-50rpx
      bg="#FCC300"
      flex
      justify-center
      items-center
      font-500
      text="#000"
      text-32rpx
      @click="submitForm">
      提交
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { addSchool, updateSchool, selectSchoolDetail } from '@/api/mySchool'
import type { FormInst } from 'nutui-uniapp'
const formRef = ref<FormInst | null>(null)
interface Form {
  id?: string
  schoolName: string
  schoolAdress: string
}

const form = ref<Form>({
  schoolName: '',
  schoolAdress: ''
})
const rules = ref({
  schoolName: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
  schoolAdress: [{ required: true, message: '请输入学校地址', trigger: 'blur' }]
})
function submitForm() {
  formRef.value?.validate().then(({ valid, errors }) => {
    if (valid) {
      console.log(form.value)
      uni.showLoading({ title: '正在提交...', mask: true })
      const submit: any = { ...form.value }
      if (form.value.id) {
        updateSchool(submit).then((res: any) => {
          uni.showToast({
            title: '修改成功',
            icon: 'none',
            duration: 3000
          })
          goBack()
        })
      } else {
        addSchool(submit).then((res: any) => {
          uni.showToast({
            title: '添加成功',
            icon: 'none',
            duration: 3000
          })
          goBack()
        })
      }
    }
  })
}
function goBack() {
  setTimeout(() => {
    uni.navigateBack({
      delta: 1 // 回退前 delta(默认为1) 页面数
    })
  }, 2000)
}
onMounted(() => {})
onLoad((options: any) => {
  if (options.id) {
    selectSchoolDetail(options.id).then((res: any) => {
      form.value = res.data.result
    })
    uni.setNavigationBarTitle({
      title: '学校详情'
    })
  }
})
</script>
<style>
page {
  --nut-cell-padding: 40rpx 0rpx;
  --nut-cell-color: #000;
}
.nut-cell-group__wrap {
  padding: 0 20rpx;
}
.nut-form-item {
  border-bottom: 1px solid #eee;
}
</style>
<style scoped lang="scss"></style>
